//
//  CategoryViewController.m
//  陶瓷
//
//  Created by 王戈 on 15/6/3.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "CategoryViewController.h"
#import "TCCategoryRightTableController.h"
#import "CategoryTableViewCell.h"
#import "CategoryLeftCell.h"
#import "CategoryBottomCell.h"
#import "CompanyDisplayViewController.h"
#import "TCSearchViewController.h"

#define LEFT_TABLEVIEW_FRAME CGRectMake(0, 0, SCREEN_WIDTH * 0.28, SCREEN_HEIGHT - 64 )
#define RIGHT_VIEW_FRAME CGRectMake(SCREEN_WIDTH * 0.28, 64, SCREEN_WIDTH * 0.72, SCREEN_HEIGHT - 64 -49)

static const CGFloat AD_WIDTH = 270;
static const CGFloat AD_HEIGHT = 100;

@interface CategoryViewController ()<UITableViewDelegate ,UITableViewDataSource ,CategoryBottomCellDelegate,SearchNavBarViewDelegate>

@property (nonatomic, strong) UITableView *leftTableView;

@property (nonatomic, strong) UIView *rightView;
@property (nonatomic, strong) UITableView *rightTableView;
@property (nonatomic, strong) UIButton * adBtn;

@property (nonatomic, strong) SearchNavBarView *searchView;

@property (nonatomic, strong) NSArray *leftDataSource;
@property (nonatomic, strong) NSMutableArray *rightDataSource;
// 看是不是在左边第一行用的
@property (nonatomic, assign) BOOL isFirst;
@property (nonatomic, strong) CategoryModel *currentCategory;

@property (nonatomic, strong) UIButton *cover;

@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" styleUIBarButtonItemStuleBorderd target:nil action nil];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:backButton];
    
    _searchView = [[NSBundle mainBundle] loadNibNamed:@"SearchNavBarView" owner:nil options:nil].firstObject;
    _searchView.frame = CGRectMake(0, 0, kDefaultWindowWidth, 44);
    _searchView.delegate = self;
    self.view.backgroundColor = TCMainBGColor;
    [self setupChildView];
    
    
    _currentCategoryID = @"sha bi ba haha ";
    //    [self.navigationItem setTitle:@"分类信息"];
    
    //    self.isFirst = YES;
}

- (void)viewWillLayoutSubviews
{
    NSLog(@"");
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar addSubview:self.searchView];
    self.searchView.address.text = [TCBaseTool sharedBaseTool].currentCityName;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self goToCategory];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.cover removeFromSuperview];
    [self.searchView removeFromSuperview];
    [SVProgressHUD dismiss];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.navigationItem setTitle:@""];
}

- (UIButton *)cover {
    if (_cover == nil) {
        _cover = [[UIButton alloc] initWithFrame:self.view.bounds];
        _cover.backgroundColor = [UIColor clearColor];
    }
    return _cover;
}

- (void)setupChildView {
    //    [self.view addSubview:self.searchView];
    
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightView];
}

- (UITableView *)leftTableView {
    if (_leftTableView == nil) {
        _leftTableView = [[UITableView alloc] initWithFrame:LEFT_TABLEVIEW_FRAME style:UITableViewStylePlain];
        
        _leftTableView.showsHorizontalScrollIndicator = NO;
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.dataSource = self;
        _leftTableView.delegate = self;
        _leftTableView.backgroundColor = [UIColor clearColor];
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.showsHorizontalScrollIndicator = NO;
        _leftTableView.bounces = NO;
    }
    return _leftTableView;
}

- (UIView *)rightView {
    if (_rightView == nil) {
        _rightView = [[UIView alloc] initWithFrame:RIGHT_VIEW_FRAME];
        _rightView.backgroundColor = TCColor(204, 204, 204, 1);
        
        [_rightView addSubview:self.rightTableView];
        [_rightView addSubview:self.adBtn];
    }
    return _rightView;
}

- (UITableView *)rightTableView {
    if (_rightTableView == nil) {
        _rightTableView = [[UITableView alloc] initWithFrame:_rightView.bounds style:UITableViewStylePlain];
        _rightTableView.y += 64;
        _rightTableView.height -= 64;
        _rightTableView.dataSource = self;
        _rightTableView.delegate = self;
        _rightTableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        _rightTableView.showsVerticalScrollIndicator = NO;
        _rightTableView.showsVerticalScrollIndicator = NO;
        _rightTableView.bounces = NO;
    }
    return _rightTableView;
}

- (NSArray *)leftDataSource {
    if (_leftDataSource == nil) {
        _leftDataSource = [NSArray array];
        [SVProgressHUD showWithStatus:@"正在请求分类数据 请稍后.."];
        [self.view addSubview:self.cover];
        
        [[TCNetworkTool sharedNetTool] categoryListWithSuccessBlocks:^(NSArray *resultArray) {
            [SVProgressHUD dismiss];
            [self.cover removeFromSuperview];
            if (_leftDataSource.count) {
                return ;
            }
            _leftDataSource = resultArray;
            [_leftTableView reloadData];
            
            [self goToCategory];
            
            
        } andFailureBlocks:^(NSString *failureMessage) {
            [SVProgressHUD dismiss];
            [self.cover removeFromSuperview];
            [STAlertView st_promptAlertWithMessage:failureMessage];
        }];
        
    }
    return _leftDataSource;
}

#pragma mark - table view

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 左边摁扭
    if ([tableView isEqual:_leftTableView]) {
        
        CategoryModel *category = _leftDataSource[indexPath.row];
        
        CategoryLeftCell *cell = [CategoryLeftCell cellWithTableView:tableView];
        cell.category = category;
        
        return cell;
    }
    // 右边摁扭
    else if ([tableView isEqual:_rightTableView]) {
        if (_isFirst) {
            CategoryTableViewCell *cell = [CategoryTableViewCell cellWithTableView:tableView];
            cell.company = _rightDataSource[indexPath.row];
            
            return cell;
        } else {
            CategoryBottomCell *cell = [CategoryBottomCell cellWithTableView:tableView];
            cell.delegate = self;
            cell.leftCompany = _rightDataSource[indexPath.row * 2];
            BOOL needIcon = [cell.leftCompany.IsVIP intValue];
            if (_rightDataSource.count > (indexPath.row * 2 +1)) {
                cell.rightCompany = _rightDataSource[indexPath.row * 2 +1];
                needIcon = (needIcon && [cell.rightCompany.IsVIP intValue] );
            }
            cell.isNeedIcon =  needIcon;
            return cell;
        }
        
    }
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        return self.leftDataSource.count;
    } else if (tableView == _rightTableView) {
        return _isFirst ? self.rightDataSource.count : (self.rightDataSource.count + 1) * 0.5 ;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 左边暂时写死
    if (tableView == _leftTableView) {
        CategoryModel *category = _leftDataSource[indexPath.row];
        return category.rowCount * 20 + 50;
    }
    // 右边详细处理
    else if (tableView == _rightTableView) {
        // 如果是推荐品牌
        if (_isFirst) {
            return kDefaultWindowWidth*0.75*7/12;
        }
        // 其他品牌 ,会分有头像和没头像两种
        else {
            
            CompanyModel *leftCompany = _rightDataSource[indexPath.row * 2];
            BOOL needIcon = [leftCompany.IsVIP intValue];
            if (_rightDataSource.count > (indexPath.row * 2 +1)) {
                CompanyModel *rightCompany = _rightDataSource[indexPath.row * 2 + 1];
                needIcon = (needIcon && rightCompany.IsVIP);
            }
            
            return needIcon ? 130 : 60;
        }
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //        CategoryBottomCell
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([[cell class] isSubclassOfClass:[CategoryBottomCell class]]) {
        return;
    }
    // 左侧table view 点击
    if (tableView == _leftTableView) {
//        [SVProgressHUD showWithStatus:@"正在获取公司数据, 请稍后.."];
        [self.view addSubview:self.cover];
        
        self.isFirst = !indexPath.row;
        
        CategoryModel *category = self.leftDataSource[indexPath.row];
        _currentCategoryID = category.Id;
        // 如果不是第一行
        if (indexPath.row) {
            CategoryLeftCell *cell = (CategoryLeftCell *)[tableView cellForRowAtIndexPath:indexPath];
            [_adBtn sd_setImageWithURL:[NSURL URLWithString:cell.category.TopCompanyImageUrl] forState:UIControlStateNormal];
            
            [[TCNetworkTool sharedNetTool] categoryGetAllCompanyWithID:category.Id andSuccessBlocks:^(NSArray *resultArray) {
//                [SVProgressHUD dismiss];
                [self.cover removeFromSuperview];
                _rightDataSource = [resultArray copy];
                [_rightTableView reloadData];
            } andFailureBlocks:^(NSString *failureMessage) {
//                [SVProgressHUD dismiss];
                [self.cover removeFromSuperview];
                [MBHUDHelper showWarningWithText:failureMessage];
            }];
        } else {
            // 如果是第一行
            [[TCNetworkTool sharedNetTool] PushCompanyListWithSuccessBlocks:^(NSArray *resultArray) {
//                [SVProgressHUD dismiss];
                [self.cover removeFromSuperview];
                _rightDataSource = [resultArray copy];
                [_rightTableView reloadData];
            } andFailureBlocks:^(NSString *failureMessage) {
//                [SVProgressHUD dismiss];
                [self.cover removeFromSuperview];
                [MBHUDHelper showWarningWithText:failureMessage];
            }];
        }
    }
    // 右侧table view 点击
    else if (tableView == _rightTableView) {
        CompanyModel *company = _rightDataSource[indexPath.row];
        if (_isFirst) {
            [SVProgressHUD showWithStatus:@"正在获取数据 请稍后.."];
            [self.view addSubview:self.cover];
            [[TCNetworkTool sharedNetTool] GetCompanyWithID:company.CompanyId andSuccessBlocks:^(NSArray *resultArray) {
                CompanyDisplayViewController *nextController = [[CompanyDisplayViewController alloc] init];
                nextController.company = resultArray.firstObject;
                [self.navigationController pushViewController:nextController animated:YES];
                
                [self.cover removeFromSuperview];
            } andFailureBlocks:^(NSString *failureMessage) {
                [MBHUDHelper showWarningWithText:failureMessage];
                [self.cover removeFromSuperview];
            }];
        } else {
            CompanyDisplayViewController *nextController = [[CompanyDisplayViewController alloc] init];
            nextController.company = _rightDataSource[indexPath.row];
            [self.navigationController pushViewController:nextController animated:YES];
        }
    }
}

- (void)categoryBtnClick:(CategoryBtn *)sender {
    CompanyDisplayViewController *nextController = [[CompanyDisplayViewController alloc] init];
    nextController.company = sender.company;
    [self.navigationController pushViewController:nextController animated:YES];
}

- (void)setIsFirst:(BOOL)isFirst {
    if (_isFirst == isFirst) {
        return;
    }
    _isFirst = isFirst;
    self.adBtn.hidden = isFirst;
    
    if (isFirst) {
        // 如果是第一行 显示table view
        _rightTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH * 0.75 - 10, [_rightTableView superview].height);
        _rightView.backgroundColor = TCColor(204, 204, 204, 1);
    } else {
        _rightTableView.frame = CGRectMake(0, CGRectGetMaxY(_adBtn.frame) + 10, SCREEN_WIDTH * 0.72 - 10, [_rightTableView superview].height - 17 - _adBtn.height);
        _rightView.backgroundColor = [UIColor whiteColor];
    }
}

- (UIButton *)adBtn {
    if (_adBtn == nil) {
        _adBtn = [[UIButton alloc] init];
        _adBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH * 0.72, kDefaultWindowWidth*0.72*5/12);
        [_adBtn setImage:[UIImage imageNamed:@"ad"] forState:UIControlStateNormal];
        [_adBtn addTarget:self action:@selector(showAD) forControlEvents:UIControlEventTouchUpInside];
        _adBtn.hidden = YES;
    }
    return _adBtn;
}

- (void)showAD {
    TCLog(@"摁扭被点击了");
}

- (void)goToCategory {
    
    if (!_leftDataSource.count) {
        return;
    }
    
    if (_currentCategoryID) {
        NSArray *categoryIDs = [_leftDataSource valueForKey:@"_Id"];
        NSInteger index = [categoryIDs indexOfObject:[NSNumber numberWithLong:[_currentCategoryID longLongValue]]];
        
        if (index == NSNotFound) {
            index = 0;
        }
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self tableView:_leftTableView didSelectRowAtIndexPath:indexPath];
        [_leftTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        _currentCategory = nil;
    }
}

- (void)gotoSearchVC
{
    self.navigationController.navigationBarHidden = YES;
    TCSearchViewController *searchVC = [[TCSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

//- (void)testRentDetail {
//    [[TCNetworkTool sharedNetTool] rentDetailWithID:@"0" andSuccessBlocks:^(NSArray *resultArray) {
//        TCLog(@"%@",resultArray);
//    } andFailureBlocks:^(NSString *failureMessage) {
//        [STAlertView st_promptAlertWithMessage:failureMessage];
//    }];
//}

@end

@implementation SearchNavBarView

- (IBAction)clickSearchButton:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(gotoSearchVC)]) {
        [self.delegate gotoSearchVC];
    }
}

@end
